package cn.tedu.csmall.commons.exception.handler;

import cn.tedu.csmall.commons.exception.ServiceException;
import cn.tedu.csmall.commons.response.JsonResult;
import cn.tedu.csmall.commons.response.ServiceCode;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    public GlobalExceptionHandler() {
        System.out.println("GlobalExceptionHandler.GlobalExceptionHandler");
    }

    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleServiceException(ServiceException e) {
        return JsonResult.fail(e);
    }

    @ExceptionHandler(BindException.class)
    public JsonResult<Void> handlerBindException(BindException e){
        String message=e.getBindingResult().getFieldError().getDefaultMessage();

        return JsonResult.fail(ServiceCode.BAD_REQUEST,message);
    }

    @ExceptionHandler(Throwable.class)
    public JsonResult<Void> handleThrowable(Throwable e) {
        e.printStackTrace();
        return JsonResult.fail(ServiceCode.INTERNAL_SERVER_ERROR, "服务器忙，请稍后再次尝试！");
    }


}